package cz.proks.bank.job;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import cz.proks.bank.domain.Payment;
import cz.proks.bank.manager.ClearingManager;
import cz.proks.bank.manager.PaymentManager;
import cz.proks.bank.manager.exeception.PaymentException;

@Service
public class ClearingCenterJob {
	private final Logger log = Logger.getLogger(getClass());
	
	@Autowired
	private ClearingManager clearingManager;
	
	@Autowired
	private PaymentManager paymentManager;
		
	@Scheduled(fixedRate = 60000)
	public void processClearingPayments() {
		log.info("processClearingPayments():: Start at " + new Date());
		try {
			List<Payment> payments = clearingManager.fetchPayments();
			
			log.info("processClearingPayments():: Fetched " + (payments != null ? payments.size() : 0) + " payments to process");
			if (payments != null)
				for (Payment payment : payments) {
					
					paymentManager.processPayment(payment);
					
					clearingManager.setPaymentResult(payment);
				}
			
			log.info("processClearingPayments():: Processing payments finished at " + new Date());
			
		} catch (PaymentException e) {
			log.error("processClearingPayments():: Processing payments failed at " + new Date() + "!", e);
		}
	}
}
